import { getCurrentInstance } from "@tarojs/taro";
import { useMount } from "ahooks";
import { useRef } from "react";

export default <T>(eventName: string, callback: (data: T) => void) => {
  const eventRef = useRef<any>();

  useMount(() => {
    const eventChannel = getCurrentInstance().page?.getOpenerEventChannel?.();
    if (eventChannel) {
      eventChannel.on?.(eventName, callback);
    }

    eventRef.current = eventChannel;
  });

  const emit = (key, data) => eventRef.current?.emit(key, data);

  return emit;
};
